library lib_baseview;

import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gameplay_flutter/lib_runtime/common/lanuage_util.dart';

import '../resource/language/generated/l10n.dart';
import 'lib_baseview.dart';

export 'package:cached_network_image/cached_network_image.dart';
export 'package:get/get.dart' hide Response;

//控制消息弹出页面的控制开关（消息页面不弹出消息提示，其他页面都要弹出消息提示）
bool isInImChatPage = false;

showWebViewDialog(BuildContext context, String url) {
  showDialog(
    context: context,
    barrierDismissible: true,
    useRootNavigator: false,
    builder: (_) {
      return Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.0),
        ),
        child: Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.0),
          ),
          height: 300,
          // child: WebViewDialogWidget(url: url)
        ),
      );
    },
  );
}

Future<void> showBottomWebView(BuildContext context, String url) =>
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        enableDrag: false,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadiusDirectional.only(
            topStart: Radius.circular(24),
            topEnd: Radius.circular(24),
          ),
        ),
        builder: (context) => Container(
              height: Get.height * 0.7,
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
              // child: WebViewDialogWidget(url: url),
            ));

SystemUiOverlayStyle systemOverlayStyleForBrightness(Brightness brightness,
    [Color? backgroundColor]) {
  final SystemUiOverlayStyle style = brightness == Brightness.dark
      ? SystemUiOverlayStyle.light
      : SystemUiOverlayStyle.dark;
  return SystemUiOverlayStyle(
    statusBarColor: backgroundColor,
    statusBarBrightness: style.statusBarBrightness,
    statusBarIconBrightness: style.statusBarIconBrightness,
    systemStatusBarContrastEnforced: style.systemStatusBarContrastEnforced,
  );
}

String imagePath(String path, {String? package}) {
  if (path.startsWith('assets/') || path.startsWith('packages/')) {
    return path;
  }
  if (package == null) {
    return 'assets/images/$path';
  }
  return 'packages/$package/assets/images/$path';
}

Widget image(
  String pathOrUrl, {
  Key? key,
  double? width,
  double? height,
  Color? color,
  BoxFit? fit,
  bool wholePath = false,
  PlaceholderWidgetBuilder? placeholder,
  LoadingErrorWidgetBuilder? errorWidget,
}) {
  if (pathOrUrl.isEmpty) {
    return placeholder?.call(Get.context!, pathOrUrl) ??
        placeholderAvatarWidget(width ?? 0, height ?? 0);
  }

  // if (pathOrUrl.startsWith('http') && pathOrUrl.endsWith('.svg')) {
  //   return SvgPicture.network(
  //     pathOrUrl,
  //     key: key,
  //     width: width,
  //     height: height,
  //     color: color,
  //     fit: fit ?? BoxFit.fill,
  //   );
  // }

  if (pathOrUrl.startsWith('http')) {
    return CachedNetworkImage(
      key: key,
      imageUrl: pathOrUrl,
      width: width,
      height: height,
      color: color,
      fit: fit,
      placeholder: placeholder,
      errorWidget: errorWidget,
    );
  }

  String assetsPath = wholePath ? pathOrUrl : 'assets/images/$pathOrUrl';
  if (assetsPath.endsWith('.svg')) {
    // return SvgPicture.asset(
    //   key: key,
    //   assetsPath,
    //   width: width,
    //   height: height,
    //   color: color,
    //   fit: fit ?? BoxFit.fill,
    // );
    return Container();
  } else {
    return LanguageUtil().isRTL()
        ? Transform.scale(
            scaleX: -1, // 水平翻转
            child: Image.asset(assetsPath,
                key: key, width: width, height: height, color: color, fit: fit),
          )
        : Image.asset(assetsPath,
            key: key, width: width, height: height, color: color, fit: fit);
  }
}

PlaceholderWidgetBuilder placeholderAvatar = (c, url) => Image.asset(
      'assets/images/contact_avatar_default.png',
    );
LoadingErrorWidgetBuilder errorAvatar = (c, url, error) => Image.asset(
      'assets/images/contact_avatar_default.png',
    );

Widget placeholderAvatarWidget(double w, double h) {
  return Image.asset(
    'assets/images/contact_avatar_default.png',
    width: w,
    height: h,
  );
}

Widget errorAvatarWidget(double w, double h) {
  return Image.asset(
    'assets/images/contact_avatar_default.png',
    width: w,
    height: h,
  );
}

extension TextStyleExt on TextStyle {
  TextStyle get withEmoji =>
      copyWith(fontFamilyFallback: ['Poppins', 'Icon-emoji']);

  TextStyle get numFontFamily => copyWith(fontFamily: 'DINAlternate-bold');

  TextStyle get enFont => copyWith(fontFamily: 'Poppins');
}

Future<List<String>?> selectPhoto(BuildContext context,
    {int selectCount = 1}) async {
  Completer<List<String>?> selectPhotoCompleter = Completer();
  showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            InkWell(
              onTap: () {
                _getImageFromGallery(context, selectPhotoCompleter,
                    count: selectCount);
                Navigator.pop(context);
              },
              child: Container(
                height: 52,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                    color: Color(0xffffffff),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8.0),
                        topRight: Radius.circular(8.0))),
                child: Text(
                  T.of(context).select_photo_album,
                  style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff000000)),
                ),
              ),
            ),
            Container(
              height: 1,
              color: const Color(0xfff5f5f5),
            ),
            InkWell(
              onTap: () {
                _getImageFromCamera(context, selectPhotoCompleter);
                Navigator.pop(context);
              },
              child: Container(
                height: 52,
                alignment: Alignment.center,
                color: const Color(0xffffffff),
                child: Text(
                  T.of(context).take_photo,
                  style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff000000)),
                ),
              ),
            ),
            Container(
              height: 10,
              color: const Color(0xfff5f5f5),
            ),
            GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child: Container(
                height: 52,
                alignment: Alignment.center,
                color: const Color(0xffffffff),
                child: Text(
                  T.of(context).cancel,
                  style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff000000)),
                ),
              ),
            )
          ],
        );
      });
  return selectPhotoCompleter.future;
}

Future _getImageFromCamera(
    BuildContext context, Completer<List<String>?> completer) async {
  // bool value =
  //     await PermissionUtil.checkAndRequestPermissionsResult(Permission.camera);
  // if (!value) return;
  // var image = await ImagePicker().pickImage(source: ImageSource.camera);
  // if (image != null) {
  //   completer.complete([image.path]);
  // } else {
  //   completer.complete(null);
  // }
}

_getImageFromGallery(BuildContext context, Completer<List<String>?> completer,
    {int count = 1}) async {
  // bool value =
  //     await PermissionUtil.checkAndRequestPermissionsResult(Permission.photos);
  // if (!value) return;
  // List<AssetEntity>? result = await AssetPicker.pickAssets(
  //   context,
  //   pickerConfig: AssetPickerConfig(
  //     maxAssets: count,
  //     requestType: RequestType.image,
  //     specialPickerType: SpecialPickerType.noPreview,
  //     previewThumbnailSize: const ThumbnailSize(200, 200),
  //     textDelegate: const AssetPickerTextDelegate(),
  //   ),
  // );
  // if (result != null && result.isNotEmpty) {
  //   List<String> re = [];
  //   for (AssetEntity entity in result) {
  //     File? file = await entity.file;
  //     if (file == null) continue;
  //     re.add(file.path);
  //   }
  //   completer.complete(re);
  // } else {
  //   completer.complete(null);
  // }
}
